package com.example.testlauncher;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;

public class ChooserActivity extends Activity {

	public static final String CLOSE_LAUNCHER = "CLOSE_LAUNCHER";
	boolean defaultAndroid = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onResume() {
		super.onResume();
		final AlertDialog.Builder adb = new AlertDialog.Builder(
				ChooserActivity.this);
		String items[] = new String[] { "App", "Default Android" };
		adb.setSingleChoiceItems(items, 0, new OnClickListener() {

			@Override
			public void onClick(DialogInterface d, int n) {
				if (n == 0) {
					defaultAndroid = false;
				} else {
					defaultAndroid = true;
				}
			}

		});
		adb.setPositiveButton("OK", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				if (defaultAndroid) {
					stopLauncher(dialog);
				} else {
					RunningTaskInfo task = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE))
							.getRunningTasks(1).get(0);

					String baseAcivity = task.baseActivity.getClassName();
					String topActivity = task.topActivity.getClassName();
					if (!baseAcivity.equals(topActivity)) {
						closeDialog(dialog);
					} else {
						stopLauncher(dialog);
					}
				}

			}

		});

		adb.setTitle("Which one?");
		adb.show();

	}

	private void stopLauncher(DialogInterface dialog) {
		Intent intent = new Intent(ChooserActivity.this, MainActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra(CLOSE_LAUNCHER, defaultAndroid);
		startActivity(intent);
		closeDialog(dialog);
	}

	private void closeDialog(DialogInterface dialog) {
		dialog.dismiss();
		finish();
	}

}
